package com.pw.study.flink.state;

import com.pw.study.flink.entities.WaterSensor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.AggregatingState;
import org.apache.flink.api.common.state.AggregatingStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

public class keyStateAgg {
    public static void main(String[] args) {
        dealList();
    }

    private static void dealList() {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);

        //输入数据
        SingleOutputStreamOperator<WaterSensor> stream = env.socketTextStream("hadoop111", 9999).map(value -> {
            String[] line = value.split(",");
            return new WaterSensor(line[0], Long.valueOf(line[1]), Integer.valueOf(line[2]));
        });

        //
        stream.keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                    private AggregatingState<WaterSensor, Double> avgState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        avgState = getRuntimeContext().getAggregatingState(new AggregatingStateDescriptor<WaterSensor, MyAvg, Double>("avgState", new AggregateFunction<WaterSensor, MyAvg, Double>() {
                            @Override
                            public MyAvg createAccumulator() {
                                System.out.println("create..............");
                                return new MyAvg();
                            }

                            @Override
                            public MyAvg add(WaterSensor value, MyAvg myAvg) {
                                System.out.println("add...... ");
                                myAvg.sum += value.getVc();
                                myAvg.count++;
                                return myAvg;
                            }

                            @Override
                            public Double getResult(MyAvg acc) {
                                System.out.println("avg.............");
                                return acc.avg();
                            }

                            @Override
                            public MyAvg merge(MyAvg myAvg, MyAvg acc1) {
                                System.out.println("merge...........");
                                return null;
                            }
                        }, MyAvg.class));
                    }

                    @Override
                    public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                        System.out.println("数据处理。。。。。。。。。");
                        avgState.add(value);

                        Double avg = avgState.get();
                        out.collect(ctx.getCurrentKey() + " 的平均水位： " + avg);
                    }
                }).print();


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class MyAvg {
        public Integer sum = 0;
        public Long count = 0L;

        public Double avg() {
            return sum * 1.0 / count;
        }
    }
}
